<template>
  <div class="test-category">
    <el-form :inline="true" :model="formData" :rules="rules" ref="formData">
      <el-form-item label="试题分类名称" prop="testName">
        <el-input
          v-model="formData.testName"
          placeholder="测试分类名称"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="状态"
          autocomplete="off"
          :clearable="true"
          :popper-append-to-body="false"
          style="width: 100px"
        >
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加测试分类</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加测试分类 -->
    <el-dialog
      title="添加测试分类"
      width="36%"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="insertForm"
        :rules="insertRules"
        ref="insertForm"
        class="insertForm"
      >
        <el-form-item
          label="测试分类名称"
          prop="testName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="insertForm.testName"
            placeholder="测试分类名称"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="测试时长"
          prop="testTime"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="insertForm.testTime"
            placeholder="测试时长（分钟）"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" :label-width="formLabelWidth">
          <el-select
            v-model="insertForm.status"
            placeholder="状态"
            autocomplete="off"
            :clearable="true"
            :popper-append-to-body="false"
            style="width: 100px"
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 表格 -->
    <div class="admin-table">
      <div class="batch-btn">
        <el-button
          type="danger"
          size="mini"
          @click="batchDelete"
          v-show="this.multipleSelection.length > 0"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          width="50"
          :index="indexConfig"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="testName"
          label="测试分类名称"
          width="240"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="testTime"
          label="测试时长（分钟）"
          width="136"
          align="center"
        ></el-table-column>
        <el-table-column label="创建时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
            <el-tag type="danger" v-else="scope.row.status === 0">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="mini"
              @click="updateStatus(scope.row, 1)"
              >启动</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="updateStatus(scope.row, 0)"
              >禁用</el-button
            >
            <el-button type="danger" size="mini" @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length > 0"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        :pager-count="7"
        style="text-align: right; margin-top: 24px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getTestCategoryList,
  insertTestCategory,
  updateTestCategoryStatus,
  batchDeleteTestCategory,
} from "@/api/admin/testCategory";
export default {
  name: "TestCategoryView",
  data() {
    return {
      formData: {
        testName: "",
        status: "",
      },
      insertForm: {
        testName: "",
        testTime: "",
        status: "",
      },
      rules: {
        testName: [{ validator: this.customValidator, trigger: "blur" }],
        status: [{ validator: this.customValidator, trigger: "blur" }],
      },
      insertRules: {
        testName: [
          { required: true, message: "请输入测试分类名称", trigger: "blur" },
        ],
        testTime: [
          { required: true, message: "请输入测试时间", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },
      page: 1,
      pageSize: 8,
      total: 0,
      currentPage: 1,
      dialogFormVisible: false,
      insertLoading: false,
      formLabelWidth: "120px",
      // 表格
      tableData: [],
      tableLoading: false,
      multipleSelection: [],
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    // 自定义校验规则
    customValidator(rule, value, callback) {
      const { testName, status } = this.formData;
      if (!testName && !status) {
        callback(new Error("请填写信息"));
      } else {
        callback();
      }
    },
    // 查询
    query() {
      this.$refs.formData.validate((v) => {
        if (v) {
          this.page = 1;
          this.getDataList();
        }
      });
    },
    // 清空
    clear() {
      this.page = 1;
      this.currentPage = 1;
      // 清空表单
      this.$refs.formData.resetFields();
      this.getDataList();
    },
    // 新增
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          try {
            this.insertLoading = true;
            const res = await insertTestCategory(this.insertForm);
            this.dialogFormVisible = false;
            await this.getDataList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 关闭新增对话框的操作
    closeDialog() {
      this.insertLoading = false;
      this.$refs.insertForm.resetFields();
    },
    // 获取测试分类列表
    async getDataList() {
      try {
        this.tableLoading = true;
        const res = await getTestCategoryList({
          ...this.formData,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.tableData = res.data.records;
        this.total = res.data.total;
      } finally {
        this.tableLoading = false;
      }
    },
    // 配置表格索引
    indexConfig(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getDataList();
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 编辑
    edit(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminEditTestCategory",
        params: { id: row.id },
      });
    },
    // 修改状态
    async updateStatus(row, status) {
      if (status === row.status) return;
      try {
        this.tableLoading = true;
        const res = await updateTestCategoryStatus({ id: row.id, status });
        await this.getDataList();
      } finally {
        this.tableLoading = false;
      }
    },
    // 删除
    async del(row) {
      this.$confirm(
        "确定删除所选数据吗？这将会删除对应的试题以及对应的考试记录，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        try {
          this.tableLoading = true;
          const res = await batchDeleteTestCategory([row.id]);
          await this.getDataList();
        } finally {
          this.tableLoading = false;
        }
      });
    },
    // 批量删除
    async batchDelete() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm(
        "确定删除所选数据吗？这将会删除对应的试题以及对应的考试记录，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        try {
          this.tableLoading = true;
          const res = await batchDeleteTestCategory(ids);
          await this.getDataList();
        } finally {
          this.tableLoading = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.test-category {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .insertForm {
    width: 440px;
  }
  .admin-table {
    .batch-btn {
      height: 28px;
      margin-bottom: 4px;
    }
  }
}
// 解决下拉框显示不完整问题
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
  margin-bottom: 0 !important;
}
</style>